package com.tang.generate.service.impl

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.github.yulichang.base.MPJBaseServiceImpl
import com.tang.generate.domain.GenField
import com.tang.generate.mapper.GenFieldMapper
import com.tang.generate.model.req.TableFieldReq
import com.tang.generate.service.IGenFieldService
import com.tang.generate.utils.GenUtils
import org.springframework.stereotype.Service
import java.util.stream.Collectors

@Service
open class GenFieldServiceImpl : IGenFieldService, MPJBaseServiceImpl<GenFieldMapper, GenField>() {


    override fun saveGenField(genTableId: Long, tableName: String) {
        val removeWrapper = Wrappers.query<GenField>()
        removeWrapper.eq("table_id", genTableId);
        baseMapper.delete(removeWrapper)
        val fieldList = baseMapper.getFiledByTable(tableName);
        val genFieldList = fieldList.stream().map {
            val genField = GenField()
            genField.tableId = genTableId;
            genField.tableField = it["COLUMN_NAME"];
            genField.isTime = it["DATA_TYPE"]?.let {dataType -> dataType == "date" || dataType == "datetime" || dataType == "time" };
            genField.tableFieldType = it["DATA_TYPE"];
            genField.name = it["COLUMN_NAME"]?.let { columnName -> GenUtils.getClassName(columnName) };
            genField.comment = it["COLUMN_COMMENT"];
            genField.fieldType = it["DATA_TYPE"]?.let { dataType -> GenUtils.getJavaType(dataType) }
            genField.type = it["DATA_TYPE"]?.let { dataType -> dataType == "smallint" }
            genField;
        }.collect(Collectors.toList<GenField>())
        genFieldList.forEach {
            save(it)
        }
    }


    override fun saveGenFields(fieldList: List<TableFieldReq>, genTableId: Long,) {
        val genFieldList = fieldList.stream().map {
            val genField = GenField()
            genField.tableId = genTableId;
            genField.tableField = it.name;
            genField.isTime = it.type?.let {dataType -> dataType == "date" || dataType == "datetime" || dataType == "time" };
            genField.tableFieldType = it.type;
            genField.name = it.javaName;
            genField.comment = it.desc;
            genField.fieldType = it.javaType
            genField.type = it.type?.let { dataType -> dataType == "smallint" }
            genField;
        }.collect(Collectors.toList<GenField>());
        genFieldList.forEach {
            saveOrUpdate(it)
        }
    }
}
